using System;
using System.Data;
using System.Collections;
using APP.QUANLY.Entity;
using APP.QUANLY.Entity.ConditionForm;

namespace APP.QUANLY.DAL
{
    /// <summary>
    /// Summary description for CA.
     /// </summary>
	public class CADao
    {
	    private string _SQLSelectByKey;
	    private string _SQLUpdate;
	    private string _SQLInsert;
	    private string _SQLDelete;
	    private string _SQLSelectAll;

        #region Properties

        public IDbConnection _dbConnection;

        public IDbConnection DbConnection
        {
            get { return _dbConnection; }
            set { _dbConnection = value; }
        }

        #endregion
        
        #region Constructor

        public CADao()
        {
            _dbConnection = null;
		    InitSqlQuery();
        }

        public CADao(IDbConnection con)
        {
            _dbConnection = con;
            InitSqlQuery();
        }

        #endregion


        private void ToLowerQuery()
        {
            _SQLDelete = _SQLDelete.ToLower();
            _SQLUpdate = _SQLUpdate.ToLower();
            _SQLInsert = _SQLInsert.ToLower();
            _SQLSelectByKey = _SQLSelectByKey.ToLower();
        }

        private void ToUpperQuery()
        {
            _SQLDelete = _SQLDelete.ToUpper();
            _SQLUpdate = _SQLUpdate.ToUpper();
            _SQLInsert = _SQLInsert.ToUpper();
            _SQLSelectByKey = _SQLSelectByKey.ToUpper();
        }

        #region InitSqlQuery
        private void InitSqlQuery()
       {
            string query;

            query = @"SELECT MACA, MANHANVIEN, NGAYBATDAU, NGAYKETTHUC, GHICHU, BATDAUCA FROM CA WHERE (MACA = @MACA)";
	        _SQLSelectByKey = query;

            query = @"UPDATE CA SET MANHANVIEN = @MANHANVIEN, NGAYBATDAU = @NGAYBATDAU, NGAYKETTHUC = @NGAYKETTHUC, GHICHU = @GHICHU, BATDAUCA = @BATDAUCA WHERE (MACA = @MACA)";
	        _SQLUpdate = query;

            query = @"INSERT INTO CA VALUES (@MANHANVIEN, @NGAYBATDAU, @NGAYKETTHUC, @GHICHU, @BATDAUCA)";
	        _SQLInsert = query;

            query = @"DELETE FROM CA WHERE (MACA = @MACA)";
	        _SQLDelete = query;

            query = @"SELECT MACA, MANHANVIEN, NGAYBATDAU, NGAYKETTHUC, GHICHU, BATDAUCA FROM CA";
	        _SQLSelectAll = query;
        }
        #endregion
        public void LoadByCommandText(string commandtext, IDbTransaction trans)
        {
            if (_dbConnection == null)
            {
                throw new Exception("Connection has not been set.");
            }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }

                command = _dbConnection.CreateCommand();
                command.CommandText = commandtext;

				if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        #region Save & Delete
        private void Save(CA obj, IDbTransaction trans, bool isExisting)
        {
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                command = _dbConnection.CreateCommand();

                if (!isExisting) { command.CommandText = _SQLInsert + ";"; }
                else { command.CommandText = _SQLUpdate + ";"; }

                         DalTools.addDbDataParameter(command, "MACA", obj.MACA, DbType.Int32);
                         DalTools.addDbDataParameter(command, "MANHANVIEN", obj.MANHANVIEN, DbType.Int32);
         DalTools.addDbDataParameter(command, "NGAYBATDAU", obj.NGAYBATDAU, DbType.DateTime);
         DalTools.addDbDataParameter(command, "NGAYKETTHUC", obj.NGAYKETTHUC, DbType.DateTime);
         DalTools.addDbDataParameter(command, "GHICHU", obj.GHICHU, DbType.String);
         DalTools.addDbDataParameter(command, "BATDAUCA", obj.BATDAUCA, DbType.Boolean);

		        if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        public void Delete(CA obj, IDbTransaction trans)
        {
            if (_dbConnection == null)
            {
                //throw new DalException("Connection has not been set.");
                throw new Exception("Connection has not been set.");
            }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }

                command = _dbConnection.CreateCommand();
                command.CommandText = _SQLDelete + ";";

                         DalTools.addDbDataParameter(command, "MACA", obj.MACA, DbType.Int32);

		        if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        public void Insert(CA obj, IDbTransaction trans)
        {
            Save(obj, trans, false);
        }
        public void Update(CA obj, IDbTransaction trans)
        {
            Save(obj, trans, true);
        }
        #endregion

        #region Command Execute & Read Properties
     
        private CAList SelectListByCommand(IDbCommand command)
        {
            CAList list = new CAList();
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {	
				CA obj;
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read()) 
					{ 
						obj = new CA();
						ReadProperties(obj, reader);
						list.Add(obj); 
					}
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }
		
        private CAList SelectListByCommand(IDbCommand command, IDbTransaction trans)
        {
            CAList list = new CAList();
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {	
				CA obj;
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
				command.Transaction = trans;
                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read()) 
					{ 
						obj = new CA();
						ReadProperties(obj, reader);
						list.Add(obj); 
					}
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }

        private void DeleteListByCommand(IDbCommand command, IDbTransaction trans)
        {
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                if (trans != null) { command.Transaction = trans; }
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
	
        private void ReadProperties(CA obj, IDataReader reader)
        {
            try
            {
                                if(!(reader["MACA"] is DBNull))
		{
			obj.MACA = (Int32)reader["MACA"];
		}
                if(!(reader["MANHANVIEN"] is DBNull))
		{
			obj.MANHANVIEN = (Int32)reader["MANHANVIEN"];
		}
                if(!(reader["NGAYBATDAU"] is DBNull))
		{
			obj.NGAYBATDAU = (DateTime)reader["NGAYBATDAU"];
		}
                if(!(reader["NGAYKETTHUC"] is DBNull))
		{
			obj.NGAYKETTHUC = (DateTime)reader["NGAYKETTHUC"];
		}
                if(!(reader["GHICHU"] is DBNull))
		{
			obj.GHICHU = (string)reader["GHICHU"];
		}
                if(!(reader["BATDAUCA"] is DBNull))
		{
			obj.BATDAUCA = (bool)reader["BATDAUCA"];
		}
            }
            catch (Exception ex)
            {
                throw new DalException("Failed to read properties from DataReader.", ex);
            }
        }
        #endregion
      
        public CA SelectByKey(Int32 MACA)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectByKey;
	                 DalTools.addDbDataParameter(command, "MACA", MACA, DbType.Int32);
      	    CAList list =  SelectListByCommand(command);

            if (list.Count == 0) { throw new Exception("No data was returned"); }
            return list[0];
        }

        public CA SelectByKey(Int32 MACA, IDbTransaction trans)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectByKey;
	                 DalTools.addDbDataParameter(command, "MACA", MACA, DbType.Int32);
      	    CAList list =  SelectListByCommand(command, trans);
			
            if (list.Count == 0) { throw new Exception("No data was returned"); }
            return list[0];
        }
		
        public CAList SelectAll()
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectAll;
      	    CAList list =  SelectListByCommand(command);
	        return list;
        }

         public CAList SelectByCommand(string Command)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = Command;
      	    CAList list =  SelectListByCommand(command);
	        return list;
        }

        public CAList SelectByCondition(CAConditionForm condt)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = "SELECT * FROM CA " + GetCondtionQuery(condt) + ";";
            FillParamToCommand(command, condt);
            CAList list = SelectListByCommand(command);
            return list;
        }

        private void DeleteByCondition(CAConditionForm condt, IDbTransaction trans)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = "DELETE FROM CA " + GetCondtionQuery(condt) + ";";
            FillParamToCommand(command, condt);
            DeleteListByCommand(command, trans);
        }

        #region Make Condition Query & Fill Param from Condition to Command
        private string GetCondtionQuery(CAConditionForm obj)
        {
            if (obj == null) { return ""; }
            string s = "";
            	if (obj.IsSetMACA)
	{
    	    s += " AND MACA = @MACA ";
	}
	if (obj.IsSetMANHANVIEN)
	{
    	    s += " AND MANHANVIEN = @MANHANVIEN ";
	}
	if (obj.IsSetNGAYBATDAU)
	{
    	    s += " AND NGAYBATDAU = @NGAYBATDAU ";
	}
	if (obj.IsSetNGAYKETTHUC)
	{
    	    s += " AND NGAYKETTHUC = @NGAYKETTHUC ";
	}
	if (obj.IsSetGHICHU)
	{
    	    s += " AND GHICHU = @GHICHU ";
	}
	if (obj.IsSetBATDAUCA)
	{
    	    s += " AND BATDAUCA = @BATDAUCA ";
	}
            if (s.Length > 0)
            {
                s =" WHERE "+s.Substring(4);
                return s;
            }
            return "";
        }

        private void FillParamToCommand(IDbCommand command, CAConditionForm obj)
        {
	    if (obj == null) { return;}
            	            if (obj.IsSetMACA)
            {
            	DalTools.addDbDataParameter(command, "MACA", obj.MACA, DbType.Int32); 
            }
            if (obj.IsSetMANHANVIEN)
            {
            	DalTools.addDbDataParameter(command, "MANHANVIEN", obj.MANHANVIEN, DbType.Int32); 
            }
            if (obj.IsSetNGAYBATDAU)
            {
            	DalTools.addDbDataParameter(command, "NGAYBATDAU", obj.NGAYBATDAU, DbType.DateTime); 
            }
            if (obj.IsSetNGAYKETTHUC)
            {
            	DalTools.addDbDataParameter(command, "NGAYKETTHUC", obj.NGAYKETTHUC, DbType.DateTime); 
            }
            if (obj.IsSetGHICHU)
            {
            	DalTools.addDbDataParameter(command, "GHICHU", obj.GHICHU, DbType.String); 
            }
            if (obj.IsSetBATDAUCA)
            {
            	DalTools.addDbDataParameter(command, "BATDAUCA", obj.BATDAUCA, DbType.Boolean); 
            }
        }
        #endregion
    }
}